 <?php 

   $app_id = "245319065513404";
   $app_secret = "e90f74a6313a60227eadcd65f72ccfb7";
   $my_url = "http://sociorating.com/facebook";

   $code = $_REQUEST["code"];

   if(empty($code)) 
   {
   	session_start();
   	session('state', md5(uniqid(rand(), TRUE))); //CSRF protection
     $dialog_url = "http://www.facebook.com/dialog/oauth?client_id=" 
       . $app_id . "&redirect_uri=" . urlencode($my_url) . "&state="
       . session('state');
       
     echo("<script> top.location.href='" . $dialog_url . "'</script>");
   }

   	session_start();
   	$state = session( 'state');
   if($_REQUEST['state'] == $state) 
   {
	session_write_close();
   	$token_url = "https://graph.facebook.com/oauth/access_token?"
       . "client_id=" . $app_id . "&redirect_uri=" . urlencode($my_url)
       . "&client_secret=" . $app_secret . "&code=" . $code;

     $response = file_get_contents($token_url);
     $params = null;
     parse_str($response, $params);

     $graph_url = 'https://graph.facebook.com/me?access_token=' . $params['access_token'];

	$fbuser = json_decode(file_get_contents($graph_url));
	$account = $fbuser->username;
	
	// logged in?	
	if(session('user') == null)
	{
		$user = UserManager::GetUserByFacebook($account);
		// no user with that Facebook name?
		if( $user == null )
		{
	    	$user = UserManager::GetUser($account);
	    	// no user with that name?
			if($user == null )
			{
				// create account
				UserManager::Signup($account, session( 'state'), $fbuser->first_name . ' ' . $fbuser->middle_name . ' ' . $fbuser->last_name, '');
				UserManager::AddFacebook($account, $account);
		     	echo("<script>top.location.href='/'</script>");
			}
			else
			{
				?>There is already an account with that name! Please login to your account before linking your Facebook.<?php
			}
		}
		else
		{
			// login
			session( 'user', $account);
			App::$Current->User = $account;
	     	echo("<script>top.location.href='/user/" . $account . "'</script>");
		}
	}
	else
	{
		// link Facebook to account
		UserManager::AddFacebook(session('user'), $account);
     	echo("<script>top.location.href='/accountsettings'</script>");
	}
}
else
{
	echo("The state does not match. You may be a victim of CSRF.");
}
